package com.foreverwin.mes.lims.controller;

import com.foreverwin.mes.common.enums.HandleEnum;
import com.foreverwin.mes.core.base.FrontPage;
import com.foreverwin.mes.core.base.AjaxResult;
import com.foreverwin.mes.core.exception.BusinessException;
import com.foreverwin.mes.core.utils.CommonMethods;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.foreverwin.mes.core.utils.StringUtils;
import com.foreverwin.mes.lims.dto.SamplingDto;
import com.foreverwin.mes.lims.enums.InspectType;
import com.foreverwin.mes.lims.model.*;
import com.foreverwin.mes.lims.service.*;
import com.foreverwin.mes.lims.util.DataValueConstant;
import com.foreverwin.mes.lims.util.NowString;
import com.foreverwin.mes.meapi.model.SfcInWork;
import com.foreverwin.mes.production.controller.SfcExController;
import com.foreverwin.mes.production.dto.SfcInWorkDto;
import com.foreverwin.mes.production.service.SfcExService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Mark
 * @since 2020-03-09
 */
@Controller
@RequestMapping("/samplings")
public class SamplingController {
    private final Logger logger = LoggerFactory.getLogger(SamplingController.class);

    @Autowired
    public SamplingService samplingService;


    @Autowired
    public InspectTaskService inspectTaskService;


    @Autowired
    public InspectPlanService inspectPlanService;

    @Autowired
    public InspectPlanDetailService inspectPlanDetailService;

    @Autowired
    public SfcExService sfcExService;

    @Autowired
    public BadEntryOfWorkshopMateService badEntryOfWorkshopMateService;

    /**
    * 根据id查询
    *
    * @param id 主键
    * @return
    */
    @ResponseBody
    @GetMapping("/{id:.+}")
    public AjaxResult getSamplingById(@PathVariable String id) {
        Sampling result;
        try {
            result = samplingService.selectById(id);
        } catch (Exception e) {
            logger.error("getSamplingById -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 查询所有数据
     *
     * @return
     */
    @ResponseBody
    @GetMapping("")
    public AjaxResult getSamplingList(Sampling sampling){
        List<Sampling> result;
        try {
            EntityWrapper<Sampling> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(sampling);
            result = samplingService.selectList(EntityWrapper);
        } catch (Exception e) {
            logger.error("getSamplingList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 分页查询数据
     *
     * @param frontPage  分页信息
     * @return
     */
    @ResponseBody
    @GetMapping("/getSamplingPageList")
    public AjaxResult getSamplingPageList(FrontPage<Sampling> frontPage, Sampling sampling){
        Page result;
        try {
            String site = CommonMethods.getSite();
            sampling.setSite(site);
            EntityWrapper<Sampling> EntityWrapper = new EntityWrapper<>();
            EntityWrapper.setEntity(sampling);
            if (frontPage.getGlobalQuery() != null && !"".equals(frontPage.getGlobalQuery().trim())) {
                //TODO modify global query
                EntityWrapper
                    .like("handle", frontPage.getGlobalQuery())
                    .or().like("site", frontPage.getGlobalQuery())
                    .or().like("inspTaskNo", frontPage.getGlobalQuery())
                    .or().like("testType", frontPage.getGlobalQuery())
                    .or().like("sampBatch", frontPage.getGlobalQuery())
                    .or().like("prdNum", frontPage.getGlobalQuery())
                    .or().like("prdName", frontPage.getGlobalQuery())
                    .or().like("creator", frontPage.getGlobalQuery())
                    .or().like("updater", frontPage.getGlobalQuery())
        ;
            }
            result = samplingService.selectPage(frontPage.getPagePlus(), EntityWrapper);
        } catch (Exception e) {
            logger.error("getSamplingPageList -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

    /**
     * 保存和修改公用
     * @param sampling  传递的实体
     * @return  null 失败  实体成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_save")
    public AjaxResult samplingSave(@RequestBody Sampling sampling) {
        String site = CommonMethods.getSite();
        String user = CommonMethods.getUser();
        //------------------------------------------------------------------------------------------------------------
        InspectTask inspectTask = inspectTaskService.selectOne(
                new EntityWrapper<InspectTask>()
                        .eq("TASK_ID",sampling.getInspTaskNo())
                        .eq("SITE",site)
        );
        if ( inspectTask == null ){
            throw BusinessException.build("任务编号【" + sampling.getInspTaskNo() +"】不存在!");
        }
        String status =  inspectTask.getTaskStatus();
        if ( !DataValueConstant.TASK_STATUS_NEW_WAIT.equals( status ) ){
            return AjaxResult.error( "任务并非处于待取样状态!不可取样。" );
        }
        String inspTaskNo = sampling.getInspTaskNo();
        String sampBatch = sampling.getSampBatch();

        String nowStr = NowString.NowString();
        Timestamp nowTs = Timestamp.valueOf(nowStr);
        String handle = HandleEnum.DEFECTIVE_RECORDS_OF_WIP.getHandle( sampling.getSite(), inspTaskNo, sampBatch);
        sampling.setHandle(handle);
        sampling.setCreatedDateTime(nowTs);
        sampling.setModifiedDateTime(nowTs);
        int count;
        try {
            Boolean isInsert = samplingService.insertOrUpdate(sampling);
            inspectTask.setTaskStatus(DataValueConstant.TASK_STATUS_SAMPLED);
            inspectTask.setUpdatedDateTime(nowTs);
            Boolean isUpdate = inspectTaskService.updateAllColumnById(inspectTask);
            count = isInsert&&isUpdate ? 1:0;
        } catch (Exception e) {
            logger.error("samplingSave -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(count == 0 ? null : sampling);
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id:.+}")
    public AjaxResult samplingDelete(@PathVariable("id") String id){
        int count;
        try {
            count = samplingService.deleteById(id) ? 1 : 0;
        } catch (Exception e) {
            logger.error("samplingDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }

    /**
     * 批量删除对象
     * @param ids 实体集合ID
     * @return  0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/_batchDelete")
    public AjaxResult removeByIds(List<String> ids){
        int count;
        try {
            count = samplingService.deleteBatchIds(ids) ? 1 : 0;
        } catch (Exception e) {
            logger.error("samplingBatchDelete -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success("count: " + count);
    }

    /**
     * 通过检验任务ID抓取检验任务资料及当前设备生产批
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/getSamplingByTaskId/{taskId:.+}")
    public AjaxResult getSamplingByTaskId(@PathVariable String taskId) {
        String site = CommonMethods.getSite();
        SamplingDto sampling = new SamplingDto();
        ArrayList<SamplingDto> result = new ArrayList<SamplingDto>();
        //--------------------------------------------------------------------------------------------------------------
        if( taskId==null && "".equalsIgnoreCase(taskId) ){
            return AjaxResult.error( "检验任务编号不能为空！" );
        }
        //--------------------------------------------------------------------------------------------------------------
        try {
            InspectTask inspectTask = new InspectTask();
            inspectTask.setTaskId(taskId);
            inspectTask.setSite(site);
            Long sampleStandard = 0l;
            List<InspectTask> result_it = inspectTaskService.selectList(inspectTask);
            if( result_it.size()>0 ){
                InspectTask it_ins = result_it.get(0);
                taskId = it_ins.getTaskId();
                String inspectType = it_ins.getInspectType();
                String inspectTypeDesc = InspectType.valueOf(inspectType).getDescription();
                String item = it_ins.getItem();
                String itemDesc = it_ins.getItemDesc();
                //--------------------------------------------------------------------------------------------------------------
                sampling.setInspTaskNo(taskId);
                sampling.setTestType(inspectTypeDesc);
                sampling.setTestTypeCode(inspectType);
                sampling.setPrdNum(item);
                sampling.setPrdName(itemDesc);
                //--------------------------------------------------------------------------------------------------------------
                String planBo = it_ins.getPlanBo();
                InspectPlanDetail inspectPlanDetail= new InspectPlanDetail();
                inspectPlanDetail.setPlanBo(planBo);
                inspectPlanDetail.setInspectType(inspectType);
                List<InspectPlanDetail> result_ipd = inspectPlanDetailService.selectList(inspectPlanDetail);
                if( result_ipd.size()>0 ) {
                    InspectPlanDetail ipd_ins = result_ipd.get(0);
                    sampleStandard = Long.valueOf(ipd_ins.getSampleStandard());
                    sampling.setSampQty(sampleStandard);
                }else{
                    throw new Exception("检验计划\'" + planBo + "\'不存在！");
                }
                InspectPlan inspectPlan= new InspectPlan();
                inspectPlan.setHandle(planBo);
                inspectPlan.setSite(site);
                List<InspectPlan> result_ip = inspectPlanService.selectList(inspectPlan);
                if( result_ip.size()>0 ){
                    InspectPlan ip_ins = result_ip.get(0);
                    String operation = StringUtils.trimHandle(ip_ins.getOperation());
                    String resource = StringUtils.trimHandle(ip_ins.getResrce());
                    List<SfcInWorkDto> sfcInWorkDtoList = sfcExService.listSfcInWork(site, resource, operation, "");
                    if( sfcInWorkDtoList.size()>0 ){
                        SfcInWorkDto sid_ins = sfcInWorkDtoList.get(0);
                        sampling.setSampBatch(sid_ins.getSfc());
                    }
                } else{
                    throw new Exception("检验计划\'" + planBo + "\'不存在！");
                }

            }else{
                throw new Exception("检验任务\'" + taskId + "\'不存在！");
            }
        } catch (Exception e) {
            logger.error("getSamplingByTaskId -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        result.add(sampling);
        return AjaxResult.success(result);
    }

    /**
     * 通过检验任务编号查询：sfc、产品编号、产品名称、检验计划维护取样标准数量
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/getSampBatch")
    public AjaxResult getResourceAndOperation(Sampling sampling){
        String site = CommonMethods.getSite();
        ArrayList<Sampling> result = new ArrayList<Sampling>();
        //-------------------------------------------------------------------------------------------------------------
        String inspTaskNo = sampling.getInspTaskNo();
        String testType = sampling.getTestType();
        if( inspTaskNo==null||"".equalsIgnoreCase(inspTaskNo) ){
            return  AjaxResult.error( "检验任务编号不能为空！" );
        }
        if( testType==null||"".equalsIgnoreCase(testType) ){
            return  AjaxResult.error( "检验类型不能为空！" );
        }
        try {
            Long sampleStandard = 0l;
            InspectTask inspectTask = new InspectTask();
            inspectTask.setTaskId(inspTaskNo);
            inspectTask.setSite(site);
            List<InspectTask> result_it = inspectTaskService.selectList(inspectTask);
            if( result_it.size()>0 ) {
                InspectTask it_ins = result_it.get(0);
                String planBo = it_ins.getPlanBo();
                if( planBo==null||"".equalsIgnoreCase(planBo) ){
                    throw new Exception("检验任务\'" + inspTaskNo + "\'的检验计划为空！");
                }else{
                    InspectPlanDetail inspectPlanDetail= new InspectPlanDetail();
                    inspectPlanDetail.setPlanBo(planBo);
                    inspectPlanDetail.setInspectType(testType);
                    List<InspectPlanDetail> result_ipd = inspectPlanDetailService.selectList(inspectPlanDetail);
                    if( result_ipd.size()>0 ) {
                        InspectPlanDetail ipd_ins = result_ipd.get(0);
                        sampleStandard = Long.valueOf(ipd_ins.getSampleStandard());
                    }else{
                        throw new Exception("检验计划\'" + planBo + "\'不存在！");
                    }
                    InspectPlan inspectPlan= new InspectPlan();
                    inspectPlan.setHandle(planBo);
                    inspectPlan.setSite(site);
                    List<InspectPlan> result_ip = inspectPlanService.selectList(inspectPlan);
                    if( result_ip.size()>0 ) {
                        InspectPlan ip_ins = result_ip.get(0);
                        String operation = StringUtils.trimHandle(ip_ins.getOperation());
                        String resource = StringUtils.trimHandle(ip_ins.getResrce());
                        List<SfcInWorkDto> sfcInWorkDtoList = sfcExService.listSfcInWork(site, resource, operation, "");
                        for( SfcInWorkDto sid_ins:sfcInWorkDtoList){
                            Sampling sampling_ins = new Sampling();
                            sampling_ins.setSampBatch(sid_ins.getSfc());
                            sampling_ins.setPrdNum( sid_ins.getItem() );
                            sampling_ins.setPrdName( sid_ins.getItemDescription() );
                            sampling_ins.setSampQty(sampleStandard);
                            result.add(sampling_ins);
                        }
                        BadEntryOfWorkshopMate badEntryOfWorkshopMate = new BadEntryOfWorkshopMate();
                        badEntryOfWorkshopMate.setSite(site);
                        List<BadEntryOfWorkshopMate> result_i =badEntryOfWorkshopMateService.selectInventoryBatchAll(badEntryOfWorkshopMate);
                        for( BadEntryOfWorkshopMate inv_ins:result_i){
                            Sampling sampling_ins_i = new Sampling();
                            sampling_ins_i.setSampBatch(inv_ins.getInventoryBatch());
                            sampling_ins_i.setPrdNum( inv_ins.getItemNo() );
                            sampling_ins_i.setPrdName( inv_ins.getItemDesc() );
                            sampling_ins_i.setSampQty(sampleStandard);
                            result.add(sampling_ins_i);
                        }
                    }
                }
            }else{
                throw new Exception("检验任务\'" + inspTaskNo + "\'不存在！");
            }
        } catch (Exception e) {
            logger.error("getSampBatch -=- {}", e.toString());
            return AjaxResult.error( e.getMessage() );
        }
        return AjaxResult.success(result);
    }

}